package com.itheima.app.manager;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.unit.DataUnit;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.itheima.autoconfig.face.AipFaceTemplate;
import com.itheima.autoconfig.huanxin.HuanXinTemplate;
import com.itheima.autoconfig.oss.OssTemplate;
import com.itheima.autoconfig.sms.SmsTemplate;
import com.itheima.domain.db.Log;
import com.itheima.domain.db.User;
import com.itheima.domain.db.UserInfo;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.db.UserService;
import com.itheima.util.ConstantUtil;
import com.itheima.util.JwtUtil;
import com.itheima.vo.ErrorResult;
import com.itheima.vo.UserInfoVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PreDestroy;
import java.io.IOException;
import java.time.Duration;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class UserManager {

    @DubboReference
    private UserService userService;

    // 1.保存用户
    public ResponseEntity save(User user) {
        Long userId = userService.save(user);
        return ResponseEntity.ok(userId);
    }

    // 2.根据手机号查询
    public ResponseEntity findByPhone(String phone) {
        int i = 1 / 0;

        User user = userService.findByPhone(phone);
        return ResponseEntity.ok(user); // 状态码固定200
    }

    @Autowired
    private SmsTemplate smsTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    // 发送短信验证码
    public void sendSms(String phone) {
        // 1.生成6位随机数
        String code = RandomUtil.randomNumbers(6);
        code = "123456";
        // 2.调用阿里云发送短信
        // smsTemplate.sendSms(phone, code);  // TODO 产品上线后实现短信发送

        // 3.将验证码存入redis
        stringRedisTemplate.opsForValue().set(ConstantUtil.SMS_CODE + phone, code, Duration.ofMinutes(5));
    }

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    // 注册登录
    public ResponseEntity regAndLogin(String phone, String verificationCode) {
        // 1.取出redis中验证码
        String codeFromRedis = stringRedisTemplate.opsForValue().get(ConstantUtil.SMS_CODE + phone);
        // 2.对比验证码
        if (!StrUtil.equals(verificationCode, codeFromRedis)) {
            return ResponseEntity.status(500).body(ErrorResult.loginError());
        }
        // 3.根据手机号查询
        User user = userService.findByPhone(phone);
        Boolean isNew;
        String type;
        if (user != null) {
            // 3-1 老用户
            isNew = false;
            type="0101";
        } else {
            // 3-2 新用户
            isNew = true;
            type="0102";
            // 保存新用户
            user = new User();
            user.setMobile(phone);
            user.setPassword("123456");
            Long userId = userService.save(user);
            user.setId(userId);

            // 向环信注册用户
            huanXinTemplate.register("HX"+userId);

            // 更新数据库表

        }

        // 4.制作jwt令牌
        user.setPassword(null);
        Map<String, Object> claims = BeanUtil.beanToMap(user);
        String token = JwtUtil.createToken(claims);

        // 5.向redis中存储用户信息（续期）
        String json = JSON.toJSONString(user);
        stringRedisTemplate.opsForValue().set(ConstantUtil.USER_TOKEN + token, json, Duration.ofDays(7));

        // 清除redis中验证码
        stringRedisTemplate.delete(ConstantUtil.SMS_CODE + phone);


        // 向mq发送一条消息
        Log log = new Log();
        log.setUserId(user.getId()); // 用户id
        log.setLogTime(DateUtil.formatDate(new Date())); // 操作时间
        log.setPlace("北京顺义");// 登录地点
        log.setEquipment("华为mate40"); // 登录设备
        log.setType(type);// 操作类型
        rabbitTemplate.convertAndSend("tanhua.log", log);


        // 6.返回结果
        HashMap<String, Object> resultMap = new HashMap<>();
        resultMap.put("isNew", isNew);
        resultMap.put("token", token);

        return ResponseEntity.ok(resultMap);
    }

    @DubboReference
    private UserInfoService userInfoService;

    // 完善用户基本信息
    public void saveUserInfo(UserInfo userInfo, String token) {
        // 1.解析token获取user对象
        User user = findUserByToken(token);
        // 2.封装userInfo
        userInfo.setId(user.getId());
        // 3.调用rpc保存
        userInfoService.save(userInfo);
    }

    // 根据token获取user对象
    public User findUserByToken(String token) {
        // 查询redis中的token
        String json = stringRedisTemplate.opsForValue().get(ConstantUtil.USER_TOKEN + token);
        // 空值处理
        if (StrUtil.isEmpty(json)) {
            return null;
        }
        // 将json转为user对象
        User user = JSON.parseObject(json, User.class);

        // 续期登录时间
        stringRedisTemplate.opsForValue().set(ConstantUtil.USER_TOKEN + token, json, Duration.ofDays(7));

        // 返回对象
        return user;
    }

    @Autowired
    private AipFaceTemplate aipFaceTemplate;

    @Autowired
    private OssTemplate ossTemplate;

    // 完善用户头像信息
    public ResponseEntity saveHeadPhoto(MultipartFile headPhoto, String token) throws IOException {
        // 1.人脸检测
        boolean checkFace = aipFaceTemplate.detect(headPhoto.getBytes());
        if (checkFace == false) { // 非人脸
            return ResponseEntity.status(500).body(ErrorResult.faceError());
        }
        // 2.将图片上传到oss
        String picUrl = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
        // 3.封装userInfo
        UserInfo userInfo = new UserInfo();
        // 3-1 用户id
        User user = findUserByToken(token);
        userInfo.setId(user.getId());
        // 3-2 用户头像
        userInfo.setAvatar(picUrl);
        // 3-3 用户封面
        userInfo.setCoverPic(picUrl);
        // 4.调用rpc更新
        userInfoService.update(userInfo);

        return ResponseEntity.ok(null);
    }

    // 查询用户信息
    public ResponseEntity findUserInfoVo(Long userId) {
        // 1.调用rpc查询
        UserInfo userInfo = userInfoService.findByUserId(userId);
        // 2.封装vo
        UserInfoVo vo = new UserInfoVo();
        BeanUtil.copyProperties(userInfo, vo);
        // 3.返回vo
        return ResponseEntity.ok(vo);
    }

    // 更新用户基本信息
    public void updateUserInfo(UserInfo userInfo, String token) {
        // 1.解析token获取userId
        User user = findUserByToken(token);
        // 2.完善userInfo对象
        userInfo.setId(user.getId());
        // 3.调用rpc更新
        userInfoService.update(userInfo);
    }
}
